package com.suray.system.run.data.mysql.analyze;

import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.system.run.data.mysql.device.entity.DeviceTaskInfoDB;
import com.suray.system.run.data.mysql.device.task.DeviceTaskInfoDBServiceImpl;
import com.suray.system.run.type.DeviceType;

import java.util.Date;

public class DeviceTaskInforMationStore {
    private DeviceTaskInfoDBServiceImpl deviceTaskInfoDBService = SpringContextHolder.getBean(DeviceTaskInfoDBServiceImpl.class);

    /**
     * 设备序列号
     */
    private String series;

    /**
     * 设备任务信息表
     */
    private DeviceTaskInfoDB deviceTaskInfoDB;

    /**
     * 设备类型
     */
    private DeviceType deviceType;

    public DeviceTaskInforMationStore(String series, DeviceType deviceType) {
        this.series = series;
        this.deviceType = deviceType;
    }

    /**
     * 查找设备任务数据
     * 如果数据不存在则创建数据
     * @return
     */
    public DeviceTaskInfoDB findDeviceTaskInfoData() {
        if (deviceTaskInfoDB != null) {
            return deviceTaskInfoDB;
        }

        deviceTaskInfoDB = deviceTaskInfoDBService.findeDeviceTaskInfoDBBySeries(series);
        if (deviceTaskInfoDB == null) {
            deviceTaskInfoDB = new DeviceTaskInfoDB();
            deviceTaskInfoDB.setSeries(series);
            deviceTaskInfoDB.setDeviceType(deviceType);
            deviceTaskInfoDBService.save(deviceTaskInfoDB);
        } else {
            Date date = new Date(System.currentTimeMillis());
            if (!deviceTaskInfoDB.checkDate(date)) {
                deviceTaskInfoDB.setCurDate(date);
                deviceTaskInfoDB.clearExecTodayTaskTime();
                deviceTaskInfoDBService.updateById(deviceTaskInfoDB);
            }
        }

        return deviceTaskInfoDB;
    }

    /**
     * 设备任务数据存储
     */
    public boolean updateDeviceTaskInfoData() {
        return deviceTaskInfoDBService.updateById(deviceTaskInfoDB);
    }
}
